<template>
  <div class="app-container">
    <div class="from">
      <div class="from-input">
        <span>角色权限字符</span>
        <el-input placeholder="请输入角色权限字符" v-model="input2"> </el-input>
      </div>
      <!-- <div class="from-input"> -->
      <!-- <span>角色ID</span>
        <el-input placeholder="请输入角色ID" v-model="input2"> </el-input>
      </div> -->
      <el-button type="primary" @click="findRole">查询</el-button>
      <el-button type="primary" @click="reset">重置</el-button>
    </div>
    <!-- 模态框 -->
    <el-dialog
      @close='closedDialog'
      :destroy-on-close='true'
      :title="isTrue ? '添加角色' : '修改角色'"
      :visible.sync="dialogFormVisible"
    >
      <el-form :model="form">
        <div class="add-form">
          <el-form-item label="角色名称" :label-width="formLabelWidth">
            <el-input v-model="form.remark" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="角色权限" :label-width="formLabelWidth">
            <el-input v-model="form.name" autocomplete="off"></el-input>
          </el-form-item>
        </div>

        <div>
          <div class="rolespan">
            <span >菜单权限分配</span>
          </div>
          <el-tree
            :data="tableData"
            show-checkbox
            ref='tree'
            node-key="id"
            :default-expanded-keys="[]"
            :default-checked-keys="rekmenuList"
            :props="{
              children: 'children',
              label: 'title',
            }"
          >
          </el-tree>

          <!-- <el-table
            :data="tableData"
            style="width: 100%"
            size="medium"
            class="table"
            ref="multipleTable"
            header-cell-class-name="table-header"
            @selection-change="handleSelectionChange"
            :tree-props="{ children: 'children' }"
            row-key="id"
            @select="rowSelect"
            @select-all="selectAll"
          >
            <el-table-column
              type="selection"
              width="55"
              align="center"
            ></el-table-column>

            <el-table-column
              prop="title"
              label="菜单权限"
              sortable
              width="663.59"
            >
            </el-table-column>
          </el-table> -->
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button
          v-if="isTrue == true"
          type="primary"
          @click="dialogFormVisible = false"
          v-on:click="addlist"
          >确 定</el-button
        >

        <el-button
          v-else
          type="primary"
          @click="dialogFormVisible = false"
          v-on:click="updatelist"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <div class="btn">
      <el-button type="primary" plain icon="el-icon-plus" @click="getmenu"
        >新增</el-button
      >
      <el-button type="success" plain icon="el-icon-plus" disabled
        >修改</el-button
      >
      <el-button type="danger" plain icon="el-icon-plus" disabled
        >删除</el-button
      >
    </div>
    <div class="table">
      <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        fit
        highlight-current-row
      >
        <el-table-column label="角色名称" width="285">
          <template slot-scope="scope">
            {{ scope.row.remark }}
          </template>
        </el-table-column>
        <el-table-column label="角色权限" width="285">
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column label="角色ID" width="285">
          <template slot-scope="scope">
            <span>{{ scope.row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="285">
          <template slot-scope="scope">
            {{ scope.row.createTime }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="285">
          <template slot-scope="scope">
            <el-button
              class="el-icon-edit-outline"
              size="mini"
              v-on:click="updateadd(scope.row)"
              type="text"
              >修改</el-button
            >

            <el-button
              class="el-icon-edit-outline"
              size="mini"
              v-on:click="getUserRoleList(scope.row.id)"
              type="text"
              >分配用户</el-button
            >
            <el-button
              class="el-icon-delete"
              size="mini"
              type="text"
              @click="deletelist(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pagination.limit"
        @current-change="handleCurrentChange"
        :current-page="page"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import {
  getRole,
  deleteRole,
  listAllMenu,
  addRole,
  getmenuList,
  getUserRoleList,
} from "@/api/role";
export default {
  created() {
    this.getRole();
    this.listAllMenu();
  },
  data() {
    return {
      //分页数据
      pagination: {
        limit: 5,
        totalpage: "",
      },
      total: 0,
      page: 1,

      tableData: [],
      //模态框数据
      dialogFormVisible: false,
      radio: 1,
      isTrue: true,
      value: "",
      value1: "",
      value2: "",
      formLabelWidth: "120px",
      list: [{}],
      input2: "",
      form: {
        id: "",
        name: "",
        createTime: "",
        remark: "",
        createTime: "",
      },
      defaultProps: {
        children: "children",
        label: "label",
      },
      listLoading: false,
      menuList: [],
      menuList1: [],
      rekmenuList: [],
      isChecked: [],
      matching: [],
    };
  },

  methods: {
    closedDialog(){
      console.log('销毁');
      this.rekmenuList=[]
    },
    // 获取角色列表
    getRole() {
      let obj = {
        page: this.page,
        limit: this.pagination.limit,
      };
      getRole(obj).then((res) => {
        this.total = res.count;
        console.log(this.total,"total");
        this.list = res.data;
        this.getpage();
      });
    },

    //分页监听器
    handleCurrentChange(value) {
      this.page = value;
      this.getRole();
    },

    // 算页数
    getpage() {
      this.pagination.totalpage = Math.ceil(this.total / this.pagination.limit);
      console.log(this.pagination.totalpage, "41414");
    },

    //重置事件
    reset() {
      (this.input2 = "")
      this.getRole();
    },
    //新增btn点击事件
    getmenu() {
      this.dialogFormVisible = true;
      this.isTrue = true;
    },
    //获取已匹配权限用户
    async getUserRoleList(id) {
      console.log(id);
      let obj = {
        roleId: id,
        page: 1,
        limit: 20,
      };
      await getUserRoleList(obj).then((res) => {
        this.matching = res.data;
        this.$store.commit("user/SET_USERROLE", this.matching);
        console.log(this.matching, "11111");
        localStorage.setItem("roleId", JSON.stringify(id));
      });
      this.$router.push("/Permissions");
    },

    handleSelectionChange(selection) {},
    //选择获取id
    // rowSelect(selection, row) {
    //   //二级父子联动
    //   if (row.children) {
    //     if (!row.isChecked) {
    //       row.children.map((item) => {
    //         this.$refs.multipleTable.toggleRowSelection(item, true);
    //         item.isChecked = true;
    //       });
    //       row.isChecked = true;
    //     } else {
    //       row.children.map((item) => {
    //         this.$refs.multipleTable.toggleRowSelection(item, false);
    //         item.isChecked = false;
    //       });
    //       row.isChecked = false;
    //     }
    //   }
    //   this.menuList = selection;
    //   console.log(selection);
    // },

    // selectAll(selection) {
    //   this.$refs.multipleTable.data.map((items) => {
    //     if (items.children) {
    //       if (!items.isChecked) {
    //         this.$refs.multipleTable.toggleRowSelection(items, true);
    //         items.isChecked = true;
    //         items.children.map((item) => {
    //           this.$refs.multipleTable.toggleRowSelection(item, true);
    //           item.isChecked = true;
    //         });
    //       } else {
    //         this.$refs.multipleTable.toggleRowSelection(items, false);
    //         items.isChecked = false;
    //         items.children.map((item) => {
    //           this.$refs.multipleTable.toggleRowSelection(item, false);
    //           item.isChecked = false;
    //         });
    //       }
    //     } else {
    //       if (!items.isChecked) items.isChecked = true;
    //       else items.isChecked = false;
    //     }
    //   });
    //   this.menuList = selection;
    // },

    load(tree, treeNode, resolve) {
      setTimeout(() => {
        resolve([]);
      }, 1000);
    },
    //获取菜单列表
    listAllMenu() {
      listAllMenu().then((res) => {
        this.tableData = res.data
        console.log('tableData',this.tableData);
      });
    },
    //查询角色
    findRole() {
      let obj = {
        roleName: this.input2,
        limit: this.pagination.limit,
        page: this.page,
      };
      getRole(obj).then((res) => {
        this.list = res.data;
        this.total = res.count;
      });
      this.page = 1;
    },
    //新增角色
    addlist() {
      // console.log('getCheckedNodes',this.$refs.tree?.getCheckedNodes());
      console.log('getCheckedNodes',this.$refs.tree?.getCheckedKeys());
      // this.menuList.forEach((item) => {
      //   this.menuList1.push(item.id);
      // });
      this.menuList1=this.$refs.tree?.getCheckedKeys()
  // return
      let obj = {
        remark: this.form.remark,
        name: this.form.name,
        menuId: this.menuList1,
      };
      addRole(obj).then((res) => {
        this.getRole();
        this.$message({
          message: "添加成功",
          type: "success",
        });
      });
      this.tableData = [];
      this.form = {
        id: "",
        name: "",
        createTime: "",
        remark: "",
        createTime: "",
      };
    },
    //删除角色
    async deletelist(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let obj = {
            roleId: id,
          };
          console.log(obj);
          deleteRole(obj)
            .then((res) => {
              this.getRole();
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            })
            .catch((err) => {});
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //获取回显菜单 修改按钮点击事件
    updateadd(value) {
      (this.dialogFormVisible = true), (this.isTrue = false);
      let obj = {
        roleId: value.id,
      };
      getmenuList(obj).then((res) => {
        console.log("rekmenuList", this.rekmenuList);
        const ids=this.getTreeId(res.data)
        console.log('ids',ids);
        this.rekmenuList = ids
        // console.log(this.tableData)
        // let arr = this.rekmenuList.find((item) => item.id == this.tableData.id);
        // console.log(arr);
      });
    },
    getTreeId(tree=[]){
     return tree.reduce((res,cur)=>{
        res.push(cur.id)
        if(cur.children?.length){
          res.push(...this.getTreeId(cur.children))
        }
        return res
      },[])
    },
    updatelist() {},
  },
};
</script>
<style scoped>
.from-input .el-input {
  margin: 0 10px;
}
.from {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 20px;
}
.from .el-input {
  width: 200px;
  height: 40px;
}
.from-input .el-select {
  margin: 0 10px;
}
.el-range-editor.el-input__inner {
  margin: 0 10px;
}
.menu-Permissions {
  border: 1px solid black;
}
.menu-Permissions li:hover {
  background-color: rgb(245, 247, 250);
}
.menu-Permissions li {
  display: flex;
}
.add-form {
  display: flex;
}
</style>
<style lang="scss">
.app-container {
  .table .el-table td {
    text-align: center !important;
  }
  .el-table_1_column_1 {
    text-align: center !important;
  }
  .el-table_1_column_2 {
    text-align: center !important;
  }
  .el-table_1_column_3 {
    text-align: center !important;
  }
  .el-table_1_column_4 {
    text-align: center !important;
  }
  .el-table_1_column_5 {
    text-align: center !important;
  }
  .el-table th > .cell {
    text-align: center !important;
  }
  .el-table-column--selection .cell {
    text-align: center !important;
    padding: 0 !important;
  }
}
.rolespan{
  margin-bottom: 10px;

}
</style>